package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CodeEnum;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;


@Controller
@ResponseBody
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    /**
     * 分页查找分类管理菜单
     * @param page 页码
     * @param pageSize 每页显示多少
     * @return 返回数据
     */
    @GetMapping("/page")
    public R<Page<Category>> pageCategory(int page, int pageSize){
        return categoryService.pageCategory(page, pageSize);
    }

    /**
     * 存储分类管理信息
     * @param category 前端传回数据
     * @return 返回是否保存成功
     */
    @PostMapping
    public R saveCategory(@RequestBody Category category){
        int status = categoryService.saveCategory(category);
        if(status == CodeEnum.ERROR_HASENTITY){
            return R.error("分类已存在");
        }
        return R.success("分类已保存");
    }

    @DeleteMapping
    public R deleteCategoryByIds(@PathParam("ids") Long ids){
        int status = categoryService.deleteCategoryByIds(ids);
        if(status == CodeEnum.ENTITY_IS_DELETE){
            return R.error("分类已被删除，请刷新页面");
        }
        if(status == CodeEnum.ERROR_HASENTITY){
            return R.error("分类有关联信息不能被删除");
        }
        return R.success("分类已删除");
    }
    @PutMapping
    public R updateCategoryById(@RequestBody Category category){
        try {
            categoryService.updateCategoryById(category);
        }catch(Exception e){

            return R.error("已存在相同分类");
        }

        return R.success("修改成功");
    }
    @GetMapping("list")
    public R getCategoryList(@PathParam("type") Integer type){
        return categoryService.getCategoryList(type);
    }
}
